package org.bp.ioc.utils;

import java.lang.reflect.Field;
import java.lang.reflect.Method;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public final class ReflectionUtils {
    private static final Logger LOGGER = LoggerFactory.getLogger(ReflectionUtils.class);

    /**
     * 获取类的实例
     * @param clazz
     * @return
     */
    public static Object newInstance(Class<?> clazz){
        Object obj;
        try {
            obj = clazz.newInstance();
        } catch (Exception e) {
            LOGGER.error(String.format("class %s newInstance failed",clazz.getName()),e);
            throw new RuntimeException(e);
        }
        return obj;
    }

    /**
     * 执行方法
     * @param obj
     * @param method
     * @param args
     * @return
     */
    public static Object invokeMethod(Object obj, Method method, Object...args){
        Object result;
        try {
            method.setAccessible(true);
            result = method.invoke(obj, args);
        } catch (Exception e) {
            LOGGER.error(String.format("method exe failed"),e);
            throw new RuntimeException(e);
        }
        return result;
    }

    /**
     * 设置属性
     * @param obj
     * @param field
     * @param value
     */
    public static void setField(Object obj, Field field,Object value){
        try {
            field.setAccessible(true);
            field.set(obj,value);
        } catch (Exception e) {
            LOGGER.error(String.format("set field failed"),e);
            throw new RuntimeException(e);
        }
    }
}
